package cn.czg.cms.service.impl;

import cn.czg.cms.entity.Comment;
import cn.czg.cms.entity.dto.CommentDTO;
import cn.czg.cms.entity.dto.SimpleCom;
import cn.czg.cms.mapper.CommentMapper;
import cn.czg.cms.service.CommentService;
import cn.czg.cms.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserService userService;

    @Override
    public void addComment(Long postId, Long parentId, Long userId, String content) {
        Comment comment = new Comment();
        comment.setPostId(postId);
        comment.setParentId(parentId == null ? 0 : parentId);

        // 延迟 parentIds 拼接逻辑（建议异步处理）
        comment.setParentIds("");

        comment.setUserId(userId);
        comment.setContent(content);
        comment.setLikeCount(0);
        comment.setStatus(1);
        comment.setCreatedAt(LocalDateTime.now());

        // 写入前确保索引建好，提高 insert 性能
        commentMapper.insert(comment);

        // 异步补 parentIds（如有必要）
        if (parentId != null && parentId > 0) {
            CompletableFuture.runAsync(() -> {
                Comment parentCom = commentMapper.selectById(parentId);
                if (parentCom != null) {
                    String parentIds = parentCom.getParentIds();
                    if (parentIds == null) {
                        parentIds = String.valueOf(0);
                    }
                    comment.setParentIds(parentIds + "," + parentId);
                    commentMapper.updateById(comment); // 补写 parentIds
                }
            });
        }
    }


    @Override
    public List<CommentDTO> getCommentsWithReplies(Long postId, int page, int size) {
        int offset = (page - 1) * size;

        // 第一步：查出分页根评论
        List<Comment> roots = commentMapper.selectRootComments(postId, offset, size);
        if (roots.isEmpty()) return List.of();

        List<Long> rootIds = roots.stream().map(Comment::getId).toList();

        // 第二步：一次查出所有这些根评论的子孙评论（通过parent_ids_）
        List<Comment> allReplies = commentMapper.selectDescendantsByParentIds(rootIds);

        // 第三步：组装树状结构
        Map<Long, CommentDTO> dtoMap = new HashMap<>();
        List<CommentDTO> result = new ArrayList<>();

        // 把根评论装入 map
        for (Comment root : roots) {
            CommentDTO dto = CommentDTO.from(root, userService);
            dto.setReplies(new ArrayList<>());
            dtoMap.put(dto.getId(), dto);
            result.add(dto);
        }

        // 先把所有评论转为DTO放进 map
        for (Comment reply : allReplies) {
            CommentDTO dto = CommentDTO.from(reply, userService);
            dto.setReplies(new ArrayList<>());
            dtoMap.put(dto.getId(), dto);
        }

        // 构建 parent -> children 关系
        for (Comment reply : allReplies) {
            CommentDTO parent = dtoMap.get(reply.getParentId());
            if (parent != null) {
                parent.getReplies().add(dtoMap.get(reply.getId()));
            }
        }

        return result;
    }

    @Override
    public IPage<SimpleCom> simpleCom(Long postId, int pageNo, int size) {
        Page<SimpleCom> page = new Page<>(pageNo, size);
        return commentMapper.simpleCom(page, postId);
    }
}
